package com.flower.sharding;

import com.common.baseException.ExceptionEnum;
import com.common.baseException.ShardingException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.util.Arrays;
import java.util.Collection;

/**
 * @ClassName DBPreciseAlgorithm
 * @Description TODO
 * @Author 张晓焕
 * @Date 2022/6/14 16:00
 * @Version 1.0
 */
@Slf4j
public class DBPreciseAlgorithm implements StandardShardingAlgorithm<Long> {
    /**
     * @author 吃麻椒的花酱
     * @date 2022/6/14 16:18
     * @Description TODO
     * @param collection 真实库集合
     * @param preciseShardingValue
     * @return java.lang.String
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        log.info("分表策略执行");
        log.info(String.valueOf(collection));
        log.info(preciseShardingValue.toString());
        for (String each : collection) {
            if (each.endsWith(String.valueOf(preciseShardingValue.getValue() % 2+1))) {
                return each;
            }
        }
        throw new ShardingException(ExceptionEnum.SHARING_ERROR);
    }

    /**
     * @author 吃麻椒的花酱
     * @date 2022/6/14 16:36
     * @Description 范围查询
     * @param collection
     * @param rangeShardingValue
     * @return java.util.Collection<java.lang.String>
     */
    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {
        log.info("库范围查询");
        log.info(String.valueOf(collection));
        log.info(rangeShardingValue.getLogicTableName());
        log.info(String.valueOf(rangeShardingValue.getValueRange().upperEndpoint()));
        log.info(String.valueOf(rangeShardingValue.getValueRange().lowerEndpoint()));
        return Arrays.asList("ds1","ds2");
    }

    @Override
    public void init() {
        log.info("库规则初始化");
    }

    @Override
    public String getType() {
        return "BD_STRATEGY";
    }
}
